package org.dromara.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import jakarta.annotation.PostConstruct;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.stereotype.Service;
import org.dromara.business.domain.bo.UserLevelBo;
import org.dromara.business.domain.vo.UserLevelVo;
import org.dromara.business.domain.UserLevel;
import org.dromara.business.mapper.UserLevelMapper;
import org.dromara.business.service.IUserLevelService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

import static org.dromara.business.constants.RedisKeys.USER_LEVEL_MAP;

/**
 * 用户等级配置Service业务层处理
 *
 * @author Eric
 * @date 2025-09-05
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserLevelServiceImpl implements IUserLevelService {

    private final UserLevelMapper baseMapper;

    /**
     * 查询用户等级配置
     *
     * @param id 主键
     * @return 用户等级配置
     */
    @Override
    public UserLevelVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public UserLevel getUserLevelByLevel(Integer level) {
        UserLevel userLevel = RedisUtils.getCacheMapValue(USER_LEVEL_MAP, level + "");
        if (userLevel == null) {
            userLevel = baseMapper.selectOne(Wrappers.lambdaQuery(UserLevel.class).eq(UserLevel::getLevel, level));
            RedisUtils.delCacheMapValue(USER_LEVEL_MAP, userLevel.getLevel() + "");
            RedisUtils.setCacheMapValue(USER_LEVEL_MAP, userLevel.getLevel() + "", userLevel);
        }
        return userLevel;
    }

    /**
     * 分页查询用户等级配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户等级配置分页列表
     */
    @Override
    public TableDataInfo<UserLevelVo> queryPageList(UserLevelBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserLevel> lqw = buildQueryWrapper(bo);
        Page<UserLevelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户等级配置列表
     *
     * @param bo 查询条件
     * @return 用户等级配置列表
     */
    @Override
    public List<UserLevelVo> queryList(UserLevelBo bo) {
        LambdaQueryWrapper<UserLevel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserLevel> buildQueryWrapper(UserLevelBo bo) {
        LambdaQueryWrapper<UserLevel> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(UserLevel::getId);
        lqw.eq(bo.getLevel() != null, UserLevel::getLevel, bo.getLevel());
        lqw.like(StringUtils.isNotBlank(bo.getLevelName()), UserLevel::getLevelName, bo.getLevelName());
        lqw.eq(bo.getPersonalHoldingRequirement() != null, UserLevel::getPersonalHoldingRequirement, bo.getPersonalHoldingRequirement());
        lqw.eq(bo.getTeamHoldingRequirement() != null, UserLevel::getTeamHoldingRequirement, bo.getTeamHoldingRequirement());
        lqw.eq(bo.getRebateRatio() != null, UserLevel::getRebateRatio, bo.getRebateRatio());
        lqw.eq(bo.getBonusRatio() != null, UserLevel::getBonusRatio, bo.getBonusRatio());
        lqw.eq(bo.getStatus() != null, UserLevel::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增用户等级配置
     *
     * @param bo 用户等级配置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UserLevelBo bo) {
        UserLevel add = MapstructUtils.convert(bo, UserLevel.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            RedisUtils.setCacheMapValue(USER_LEVEL_MAP, add.getLevel() + "", add);
        }
        return flag;
    }

    /**
     * 修改用户等级配置
     *
     * @param bo 用户等级配置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UserLevelBo bo) {
        UserLevel update = MapstructUtils.convert(bo, UserLevel.class);
        validEntityBeforeSave(update);
        if (baseMapper.updateById(update) > 0) {
            RedisUtils.delCacheMapValue(USER_LEVEL_MAP, update.getLevel() + "");
            RedisUtils.setCacheMapValue(USER_LEVEL_MAP, update.getLevel() + "", update);
            return true;
        }
        return false;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserLevel entity){
        if (entity.getId() == null) {
            boolean exits = baseMapper.exists(Wrappers.lambdaQuery(UserLevel.class)
                .eq(UserLevel::getLevel, entity.getLevel()));
            if (exits) {
                throw new ServiceException("等级已存在");
            }
        } else {
            boolean exits = baseMapper.exists(Wrappers.lambdaQuery(UserLevel.class)
                .eq(UserLevel::getLevel, entity.getLevel())
                .ne(UserLevel::getId, entity.getId()));
            if (exits) {
                throw new ServiceException("等级已存在");
            }
        }
    }

    /**
     * 校验并批量删除用户等级配置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<UserLevel> list = baseMapper.selectByIds(ids);
        if (baseMapper.deleteByIds(ids) > 0) {
            if (CollUtil.isNotEmpty(list)) {
                for (UserLevel userLevel : list) {
                    RedisUtils.delCacheMapValue(USER_LEVEL_MAP, userLevel.getLevel() + "");
                }
            }
            return true;
        }


        return false;
    }

    @PostConstruct
    public void init() {
        log.info("加载用户等级配置缓存");
        List<UserLevel> list = baseMapper.selectList(Wrappers.lambdaQuery(UserLevel.class)
            .eq(UserLevel::getStatus, 1));
        RedisUtils.deleteObject(USER_LEVEL_MAP);
        if (CollUtil.isNotEmpty(list)) {
            for (UserLevel userLevel : list) {
                RedisUtils.setCacheMapValue(USER_LEVEL_MAP, userLevel.getLevel() + "", userLevel);
            }
        }
    }
}
